import os
import random,time

# 上传头像
def uploadFileAssets(request,pos,field='file'):
    # 接收上传的文件
    file = request.FILES.get(field, None)
    if not file:
        return None
    ext = file.name.split('.').pop()
    return uploadFile(file, pos, ext)

# 保存文件
def uploadFile(file, pos="files", ext="png"):
    name = str(random.randint(10000, 99999) + time.time()) + '.' + ext
    try:
        # 注意，这个路径和返回的路径不太一样，是真实路径
        with open(f'./static/assets/{pos}/{name}', 'wb+') as fp:
            ## 分块写入文件
            for chunk in file.chunks():
                fp.write(chunk)
        filename = f'/static/assets/{pos}/{name}'
        print("链接是", filename)
        return filename
    except Exception as e:
        print("error is ", e)
        return None

# 移除文件
def removeFile(url):
    # "/static/assets/files/1669112180.0511813.xlsx"
    try:
        if not url:
            return True
        url = "." + url
        if os.path.exists(url):
            print("已经成功删除文件", url)
            os.remove(url)
        return True
    except Exception as e:
        print("error is", e)
        return None